package com.whity.towerdefense.model;

import java.io.IOException;
import java.util.Vector;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

public class Wave implements I_Tickable
{
	// =============================================================
	// Private attributs :
	
	private static final String TAG = "com.djm.test03.model";
	
	private Vector<SpawnPoint> 	m_SpawnPoints;
	private Vector<SpawnPoint>	m_ActiveSpawningPoint;
	private int					m_WaveTimeElapsed;
	
	// =============================================================
	// Public functions
	
	public Wave(XmlPullParser p_XmlParser) throws ParsingException, XmlPullParserException, IOException
	{
		m_WaveTimeElapsed = 0;
		if(!p_XmlParser.getName().equals("Wave"))
    	{
			Log.w(TAG, "Can't initialise a Wave with an Xml item : " + p_XmlParser.getName());
			throw(new ParsingException("Can't initialise a Wave with an Xml item : " + p_XmlParser.getName()));
		}
		
		m_SpawnPoints = new Vector<SpawnPoint>();
		m_ActiveSpawningPoint = new Vector<SpawnPoint>();
		
		try
		{
			int eventType;
			eventType = p_XmlParser.getEventType();
			while(!(eventType == XmlPullParser.END_TAG && p_XmlParser.getName().equals("Wave")))
			{
				if(eventType == XmlPullParser.START_TAG)
	            {
					if(p_XmlParser.getName().equals("SpawnPoint"))
			    	{
						m_SpawnPoints.add(new SpawnPoint(p_XmlParser));
			    	}
	            }
				eventType = p_XmlParser.next();
			}
		}
		catch (XmlPullParserException e)
		{
			Log.w(TAG, "Can't parse Xml during wave initialisation. Wave's start time : " + m_WaveTimeElapsed);
			throw(e);
		} catch (IOException e)
		{
			Log.w(TAG, "Can't parse Xml during wave initialisation (IO). Wave's start time : " + m_WaveTimeElapsed);
			throw(e);
		}
	}

	public boolean GameTick(int p_Ms)
	{
		m_WaveTimeElapsed += p_Ms;
		for(int i = 0 ; i < m_SpawnPoints.size() ; i++)
		{
			SpawnPoint sp = m_SpawnPoints.get(i);
			if(sp.GetStartTime() < m_WaveTimeElapsed)
			{
				GameModel.GAME_THREAD.AddTickable(sp);
				synchronized(m_ActiveSpawningPoint)
				{
					m_ActiveSpawningPoint.add(sp);
				}
				m_SpawnPoints.remove(sp);
				i--;
			}
		}
		synchronized(m_ActiveSpawningPoint)
		{
			for(int i = 0 ; i < m_ActiveSpawningPoint.size() ; i++)
			{
				SpawnPoint sp = m_ActiveSpawningPoint.get(i);
				if(!sp.IsActif())
				{
					m_ActiveSpawningPoint.remove(sp);
					i--;
				}
			}
		}
		
		return true;
	}
	
	
	public void RecalculatePathfinding()
	{
		// TODO implementation
		synchronized(m_ActiveSpawningPoint)
		{
			for(SpawnPoint sp : m_ActiveSpawningPoint)
			{
				sp.RecalculatePathfinding();
			}
		}
	}
	
	// =============================================================
}
